package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.dto.course.CourseDTO;
import com.qk.entity.Course;
import com.qk.management.mapper.CourseMapper;
import com.qk.management.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Just、倾城
 * @created 2025-10-12
 * @description
 *
 */
@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;



    @Override
    public List<Course> listBySubject(String subject) {
        // 参数校验
        if(ObjectUtil.isEmpty( subject)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        List<Course> courses = courseMapper.selectBySubject(subject);
        return courses;
    }

    @Override
    public List<Course> listAll() {
        // 参数校验 无
        return courseMapper.listAll();
    }


    @Override
    public void update(Course course) {
        // 参数校验
        if(ObjectUtil.isNull(course.getUpdateTime())){
            course.setUpdateTime(LocalDateTime.now());
        }
        courseMapper.update(course);
    }



    @Override
    public Course getById(Integer id) {
        // 参数校验
        if(ObjectUtil.isNull( id)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        return courseMapper.selectById(id);
    }



    @Override
    public void delete(Integer id) {
        // 参数校验 无
        courseMapper.deleteById(id);
    }

    @Override
    public void add(Course course) {
        // 参数校验 无

        course.setUpdateTime(LocalDateTime.now());
        course.setCreateTime(LocalDateTime.now());
        courseMapper.add(course);
    }



    @Override
     public PageResult<Course> page(CourseDTO courseDTO) {
        // 参数校验
        if(BeanUtil.hasNullField(courseDTO,"name","subject","target")){
          CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }

        PageHelper.startPage(courseDTO.getPage(),courseDTO.getPageSize());
        List<Course> courseList = courseMapper.page(courseDTO);
        Page<Course> pageInfo = (Page<Course>) courseList;
        return PageResult.<Course>builder()
                .total(Integer.getInteger(pageInfo.getTotal()+""))
                .rows(pageInfo.getResult())
                .build();
    }
}
